﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MementoClient.Interfaces;
using Newtonsoft.Json;
using MementoClient.Logging;

namespace MementoClient.Classes
{
    public class GetAsyncService : IGetAsyncService
    {
        public Task<X> GetAsync<X>(string relativeUrl)
        {
            var logger = new Logger();
            var serverUrl = ConfigurationManager.AppSettings["MementoServerUrl"];
            var client = Helpers.GetHttpClient();
            
            if (String.IsNullOrEmpty(serverUrl))
            {
                logger.Fatal("A server URL for the Memento API services must be specified in the application configuration");
                return null;
            }
            
            var task = client.GetAsync(serverUrl + relativeUrl);
            try
            {
                return task.ContinueWith(a =>
                {
                    var response = a.Result.Content;
                    var taskReturningObject = response.ReadAsStringAsync().ContinueWith(b =>
                    {
                        return JsonConvert.DeserializeObject<X>(b.Result);
                    });
                    return taskReturningObject;
                }).Unwrap();
            }
            catch(JsonReaderException)
            {
                logger.Fatal(String.Format("Could not deserialize the response for object type {0}", typeof(X)));
                return null;
            }
        }
    }
}
